<template>
  <div class="vulnerability-management">
    <!-- 筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-content">
        <DynamicForm
          ref="searchFormRef"
          v-model="filterForm"
          :form-config="filterFormConfig"
          :gutter="16"
          label-width="100px"
          type="search"
          @search="handleSearch"
          @reset="handleReset"
        >
        </DynamicForm>
      </div>
    </el-card>

    <!-- 漏洞列表 -->
    <el-card class="table-card" :body-style="{ padding: '15px' }">
      <DynamicTable
        ref="tableRef"
        :data="list"
        :columns="tableColumns"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        border
        @size-change="handleSizeChange"
        @current-page-change="handlePageChange"
      >
        <template #toolbar-left>
          <el-button type="primary" @click="handleUploadPoc">上传POC</el-button>
          <el-button type="primary" @click="handleImportExcel"
            >导入漏洞库</el-button
          >
        </template>
        <template #severity="{ row }">
          <el-tag
            :type="
              row.severity === 'critical'
                ? 'danger'
                : row.severity === 'high'
                ? 'warning'
                : row.severity === 'medium'
                ? 'info'
                : row.severity === 'low'
                ? 'success'
                : ''
            "
            size="small"
          >
            {{ getSeverityText(row.severity) }}
          </el-tag>
        </template>
        <template #action="{ row }">
          <el-button size="small" @click="openDetailModal(row)" type="info">
            详情
          </el-button>
          <el-button size="small" @click="handleTest(row)" type="primary">
            测试
          </el-button>
        </template>
      </DynamicTable>
    </el-card>

    <!-- 漏洞详情弹窗 -->
    <DetailModal
      v-model="detailVisible"
      :vulnerability="currentVulnerability"
    />

    <!-- 上传POC弹窗 -->
    <UploadPocModal v-model="uploadPocVisible" @uploaded="handleUploaded" />

    <!-- 导入Excel弹窗 -->
    <ImportExcelModal v-model="importExcelVisible" @uploaded="handleUploaded" />

    <!-- 漏洞测试弹窗 -->
    <TestModal
      v-model="testVisible"
      :vulnerability="currentTestVulnerability"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage } from "element-plus";
import DynamicForm from "@/components/DynamicForm/index.vue";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { DynamicFormInstance } from "@/components/DynamicForm/types";
import type { DynamicTableInstance } from "@/components/DynamicTable/types";
import type { FormItemConfig } from "@/components/DynamicForm/types";
import type {
  TableColumn,
  PaginationConfig,
} from "@/components/DynamicTable/types";
import DetailModal from "./components/DetailModal.vue";
import UploadPocModal from "./components/UploadPocModal.vue";
import ImportExcelModal from "./components/ImportExcelModal.vue";
import TestModal from "./components/TestModal.vue";
import { getVulnerabilityList, getVulnerabilityDetail } from "../../servers";

// 页面状态
const loading = ref(false);
const detailVisible = ref(false);
const currentVulnerability = ref<any>({});
const uploadPocVisible = ref(false);
const importExcelVisible = ref(false);
const testVisible = ref(false);
const currentTestVulnerability = ref<any>({});

// 筛选表单
const searchFormRef = ref<DynamicFormInstance>();
const filterForm = reactive({
  severity: "",
  has_cve: undefined as boolean | undefined,
  tags: "",
  keyword: "",
  is_active: true,
});

// 筛选表单配置
const filterFormConfig = computed<FormItemConfig[]>(() => [
  {
    key: "severity",
    name: "严重程度",
    type: "select",
    placeholder: "请选择严重程度",
    params: { clearable: true },
    options: [
      { label: "严重", value: "critical" },
      { label: "高危", value: "high" },
      { label: "中危", value: "medium" },
      { label: "低危", value: "low" },
      { label: "信息", value: "info" },
      { label: "未知", value: "unknown" },
    ],
  },
  {
    key: "has_cve",
    name: "CVE编号",
    type: "select",
    placeholder: "请选择",
    params: { clearable: true },
    options: [
      { label: "有CVE", value: true },
      { label: "无CVE", value: false },
    ],
  },
  {
    key: "tags",
    name: "标签",
    type: "input",
    placeholder: "请输入标签，多个用逗号分隔",
    col: { span: 5 },
  },
  {
    key: "keyword",
    name: "关键词",
    type: "input",
    placeholder: "请输入漏洞名称或描述关键词",
    col: { span: 5 },
  },
]);

// 表格列配置
const tableColumns: TableColumn[] = [
  {
    label: "漏洞名称",
    prop: "name",
    minWidth: 200,
    showOverflowTooltip: true,
  },
  {
    label: "CVE编号",
    prop: "cve_id",
    minWidth: 150,
    formatter: (row) => {
      return row.cve_id || "-";
    },
  },
  {
    label: "严重程度",
    prop: "severity",
    minWidth: 100,
    slot: "severity",
  },
  {
    label: "CVSS",
    prop: "cvss_score",
    minWidth: 80,
    align: "center",
    formatter: (row) => {
      return row.cvss_score !== undefined && row.cvss_score !== null
        ? row.cvss_score.toFixed(1)
        : "-";
    },
  },
  {
    label: "操作",
    width: 150,
    fixed: "right",
    slot: "action",
  },
];

// 表格数据
const list = ref<any[]>([]);

// 分页配置
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

// 表格引用
const tableRef = ref<DynamicTableInstance>();

// 获取严重程度文本
const getSeverityText = (severity: string): string => {
  const map: Record<string, string> = {
    critical: "严重",
    high: "高危",
    medium: "中危",
    low: "低危",
    info: "信息",
    unknown: "未知",
  };
  return map[severity] || severity;
};

// 获取漏洞列表
const fetchList = async () => {
  loading.value = true;
  try {
    const params: any = {
      page: pagination.currentPage,
      page_size: pagination.pageSize,
    };

    // 添加筛选条件
    if (filterForm.severity) {
      params.severity = filterForm.severity;
    }
    if (filterForm.has_cve !== undefined) {
      params.has_cve = filterForm.has_cve;
    }
    if (filterForm.tags) {
      params.tags = filterForm.tags;
    }
    if (filterForm.keyword) {
      params.keyword = filterForm.keyword;
    }
    if (filterForm.is_active !== undefined) {
      params.is_active = filterForm.is_active;
    }

    const { data } = await getVulnerabilityList(params);
    if (data) {
      list.value = data.vulnerabilities || [];
      pagination.total = data.pagination?.total_pages || 0;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取漏洞列表失败");
  } finally {
    loading.value = false;
  }
};

// 筛选操作
const handleReset = () => {
  searchFormRef.value?.resetFields();
  filterForm.severity = "";
  filterForm.has_cve = undefined;
  filterForm.tags = "";
  filterForm.keyword = "";
  filterForm.is_active = true;
  pagination.currentPage = 1;
  fetchList();
};

const handleSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};

// 分页操作
const handlePageChange = (page: number) => {
  pagination.currentPage = page;
  fetchList();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  fetchList();
};

// 打开详情弹窗
const openDetailModal = async (row: any) => {
  try {
    loading.value = true;
    const { data } = await getVulnerabilityDetail(row.id);
    if (data) {
      currentVulnerability.value = data;
      detailVisible.value = true;
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "获取漏洞详情失败");
  } finally {
    loading.value = false;
  }
};

// 测试漏洞
const handleTest = (row: any) => {
  currentTestVulnerability.value = row;
  testVisible.value = true;
};

// 打开上传POC弹窗
const handleUploadPoc = () => {
  uploadPocVisible.value = true;
};

// 打开导入Excel弹窗
const handleImportExcel = () => {
  importExcelVisible.value = true;
};

// 上传完成后的回调
const handleUploaded = () => {
  fetchList();
};

// 初始化
onMounted(() => {
  fetchList();
});
</script>

<style scoped lang="scss">
.vulnerability-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .filter-card,
  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .filter-content {
    padding: 5px 0;
  }
}
</style>
